package com.sgb.jicai.view.fragment;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.google.android.material.tabs.TabLayout;
import com.sgb.jicai.R;
import com.sgb.jicai.base.JiCaiBaseApi;
import com.sgb.jicai.databinding.FragmentHomeJicaiXufangBinding;
import com.sgb.jicai.entity.CentralizedMiningEntity;
import com.sgb.jicai.viewmodel.HomeJiCaiXuFangModel;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.view.widget.WhitePopWindow;
import com.swgk.core.base.BaseHeightViewPagerFragment;
import com.swgk.core.view.entity.MenuEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.jicai.entity.JiCaiHomeListRequestBean;
import com.sgb.jicai.event.JiCaiEventEntity;
import com.sgb.jicai.view.adapter.CentralizedMiningCuttingLineAdapter;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 集采首页需方列表
 */
public class HomeJiCaiXuFangFragment extends BaseHeightViewPagerFragment {

    HomeJiCaiXuFangModel mModel;
    FragmentHomeJicaiXufangBinding mBind;
    private CentralizedMiningCuttingLineAdapter mAdapter;
    //集采方式
    private List<PickSelectEntity> jicaiTypeList;
    private WhitePopWindow pickMethodPopWindow;
    private JiCaiHomeListRequestBean jiCaiHomeList;
    //tabtitle列表集合
    private List<MenuEntity> tabTitleList;
    private MenuEntity all;
    private int index = 0;

    public static HomeJiCaiXuFangFragment newInstance() {
        HomeJiCaiXuFangFragment fragment = new HomeJiCaiXuFangFragment();
        Bundle args = new Bundle();
        args.putInt(BaseHeightViewPagerFragment.ARG_PARAM_POS, 0);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBind = DataBindingUtil.inflate(inflater, R.layout.fragment_home_jicai_xufang, container, false);
        mModel = new ViewModelProvider(this).get(HomeJiCaiXuFangModel.class);
        mModel.setActivity(HomeJiCaiXuFangFragment.this);
        mBind.seeMore.setOnClickListener(this);
        mBind.seeMore.setEnabled(true);
        return mBind.getRoot();
    }

    @Override
    protected void initView() {
        if (jiCaiHomeList == null) {
            jiCaiHomeList = new JiCaiHomeListRequestBean();
        }
        initListData();
        //集采方式
        pickMethodPopWindow = new WhitePopWindow(this.getContext());
        pickMethodPopWindow.setBgView(mBind.grayLayout);
        pickMethodPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                index = ((int) key3);
                //集采类别
                jiCaiHomeList.setGroupbuyClass((String) key1);
                String name = (String) key2;
                mBind.jicaiType.setText(name);
                setTextViewBg(mBind.jicaiType, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
                //如果集采类型（商品材料、机械租赁、设备租赁）变动那么重新获取右侧TabTitleList数据信息
                mModel.getTypeDatesList(jiCaiHomeList.getGroupbuyClass());
            }
        });
        pickMethodPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (null == jiCaiHomeList.getGroupbuyClass() || "".equals(jiCaiHomeList.getGroupbuyClass())) {
                    setTextViewBg(mBind.jicaiType, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
                }
            }
        });
        mBind.jicaiType.setOnClickListener(this);
        mBind.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if (tabTitleList != null && tabTitleList.get(position) != null) {
                    jiCaiHomeList.setTypeNo(tabTitleList.get(position).getId());
                }
                mBind.seeMore.setEnabled(true);
                mBind.seeMore.setText("更多");
                mBind.seeMore.setTextColor(getActivity().getResources().getColor(R.color.color_secondary_blue));
                //获取列表信息
                mModel.getJiCaiList(jiCaiHomeList, false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mBind.recyclerView.setNestedScrollingEnabled(false);
        mAdapter = new CentralizedMiningCuttingLineAdapter(getContext(), new ArrayList<>());
        mBind.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBind.recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClick(new AdapterOnItemClick<CentralizedMiningEntity>() {
            @Override
            public void onItemClick(CentralizedMiningEntity entity, int position) {
                mModel.getH5Url(entity.getNo());
            }
        });


    }

    private void initListData() {
        //获取列表信息
        jiCaiHomeList.setGroupbuyClass("1");
        jiCaiHomeList.setTypeNo("");
        mModel.getJiCaiList(jiCaiHomeList, false);
        mModel.groupBuyClassList();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.jicai_type) {
            if (null == jicaiTypeList || jicaiTypeList.size() == 0) {
                mModel.groupBuyClassList();
            }
            pickMethodPopWindow.showPopwindow0(mBind.jicaiTop);
            pickMethodPopWindow.setData(jicaiTypeList, index);
        } else if (id == R.id.see_more) {
            mModel.getJiCaiList(jiCaiHomeList, true);
        }
    }


    public void setRefresh() {
        mBind.seeMore.setEnabled(true);
        mBind.seeMore.setText("更多");
        mBind.seeMore.setTextColor(getActivity().getResources().getColor(R.color.color_secondary_blue));
        mModel.getJiCaiList(jiCaiHomeList, false);
    }

    @Override
    protected void onLazyLoad() {
    }

    public void showList(List<CentralizedMiningEntity> list, boolean loadMore) {
        if (loadMore) {
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            } else {
                mBind.seeMore.setEnabled(false);
                mBind.seeMore.setText("没有更多了");
                mBind.seeMore.setTextColor(getActivity().getResources().getColor(R.color.color_969696));
            }
        } else {
            if (list != null && list.size() > 0) {
                mBind.llRecyclerView.setVisibility(View.VISIBLE);
                mBind.emptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
                mBind.seeMore.setEnabled(true);
            } else {
                mAdapter.clearDatas();
                mBind.emptyView.setVisibility(View.VISIBLE);
                mBind.llRecyclerView.setVisibility(View.GONE);
            }
        }
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof CentralizedMiningFragment5) {
            ((CentralizedMiningFragment5) parentFragment).hideRefresh();
        }
    }

    public void showUrl(String url) {
        JiCaiBaseApi.startWeb(getActivity(), url);
    }

    //    返回列表顶部
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(JiCaiEventEntity event) {
        if (event.getCode() == EventConstant.EVENT_JICAI_BACK_TO_TOP) {
            mBind.recyclerView.scrollToPosition(0);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //集采分类
    public void setTypeDatas(List<PickSelectEntity> data) {
        if (jicaiTypeList != null && jicaiTypeList.size() > 0) {
            jicaiTypeList.clear();
        }
        this.jicaiTypeList = data;
        index = 0;
        if (jiCaiHomeList != null && data != null && data.size() > 0) {
            if (data.get(0) != null) {
                //设置初始值，默认选择商品材料
                jiCaiHomeList.setGroupbuyClass(data.get(0).getNo());
                mBind.jicaiType.setText(data.get(0).getPickerViewText());
                setTextViewBg(mBind.jicaiType, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
                //获取tabtitlelist的接口信息
                mModel.getTypeDatesList(jiCaiHomeList.getGroupbuyClass());
            }
        }

    }

    private void setTextViewBg(TextView textView, int bg, int img, int textColor) {
        textView.setBackground(getResources().getDrawable(bg));
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());  //此为必须写的
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }

    //tablayout的数据展示信息
    public void setTypesFirstDatas(List<MenuEntity> data) {
        this.tabTitleList = data;
        mBind.tabLayout.removeAllTabs();
        //默认插入全部选项，如果不需要全部那就知识掉下面代码
        all = new MenuEntity();
        all.setId("");
        all.setName("全部");
        data.add(0, all);

        for (MenuEntity MenuEntity : data) {
            //tablayout根据返回数据来加载title列表信息
            mBind.tabLayout.addTab(mBind.tabLayout.newTab().setText(MenuEntity.getName()));
        }
        //设置默认选中第一个数据信息
        if (jiCaiHomeList != null && data.size() > 0) {
            mBind.tabLayout.getTabAt(0).select();
            mBind.tabLayout.scrollTo(0, 0);
        }
    }

    public void initializePop() {
        if (mModel == null) return;
        //每次进来获取集采分类（商品材料、机械租赁、设备租赁列表信息）
        if (mModel != null) {
            mModel.groupBuyClassList();
        }
        if (jiCaiHomeList == null) {
            jiCaiHomeList = new JiCaiHomeListRequestBean();
        }
        jiCaiHomeList.setGroupbuyClass("1");
        initListData();
    }
}
